package com.atguigu.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.atguigu.oss.service.OssService;
import com.atguigu.oss.util.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = ConstantPropertiesUtil.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = file.getInputStream();
            //String fileName= file.getOriginalFilename();
            //2022/3/17
            String filePath = new DateTime().toString("yyyy/MM/dd");
            //文件名：uuid.扩展名
            String fileName = file.getOriginalFilename();
            //sysc-4hhd-df74 变 sysc4hhddf74
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            fileName = fileName.substring(fileName.lastIndexOf("."));
            fileName = uuid + fileName;
            String fileUrl = filePath + "/" + fileName;
            String url = null;
            // 创建PutObjectRequest对象。
            //第一个参数：bucket名称
            //第二个参数：上传到oss的文件路径和文件名 aa/bb/.jpg
            //第三个参数：上传文件的输入流
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileUrl,inputStream );
            // 上传文件。
            ossClient.putObject(putObjectRequest);
            url = "http://" + bucketName + "." + endpoint + "/" + fileUrl;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

    }
    }

